package edu.cs.usask.ca.silver.plugin.rcp.handlers.database;

import org.apache.log4j.Logger;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.handlers.HandlerUtil;

import edu.cs.usask.ca.silver.plugin.rcp.dao.SilverBusinessLogicController;
import edu.cs.usask.ca.silver.plugin.rcp.dialogs.database.SpecifyNewDatabaseConnectionDialog;
import edu.cs.usask.ca.silver.plugin.rcp.views.projectviewer.ProjectViewI;

public class SpecifyRemoteDatabaseConnectionForProjectViewHandler extends
		AbstractHandler {

	private final String viewParameter = "projectviewid";
	private static Logger logger = Logger.getLogger(SpecifyRemoteDatabaseConnectionForProjectViewHandler.class);

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		ProjectViewI view = (ProjectViewI) HandlerUtil
				.getActiveWorkbenchWindow(event).getActivePage()
				.findView(event.getParameter(viewParameter));

		// Setup database connection for view
		boolean flag = false;

		SpecifyNewDatabaseConnectionDialog dialog = new SpecifyNewDatabaseConnectionDialog(
				HandlerUtil.getActiveWorkbenchWindow(event).getShell());

		dialog.create();

		if (dialog.open() == Window.OK) {
			SilverBusinessLogicController
					.writeNewDatabaseConnectionToPreference(
							dialog.getDatabaseLocation(),
							dialog.getDatabaseName(), dialog.getDatabasePort(),
							dialog.getDatabaseUser(), dialog.getDatabasePass());
			logger.info("connection set");
			flag = true;
		}

		if (flag) {
			//TODO nullpointer exception? why?
			view.resetAssociatedStorage(dialog.getDatabaseInstance());
		}
		
		return null;
	}

}
